//
//  ClubGameDetailCommitDetailVC.swift
//  77Club
//
//  Created by Apple on 2024/9/4.
//

import UIKit
import ZLPhotoBrowser

class ClubGameDetailCommitDetailVC: ClubBaseViewController, RaeAnimationProtocol {
    
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("GameDetail_more").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(16.font_semiBold).text("评价详情").end()
    private var bottomView = ClubDynamicDetailBottomView()
    private let commitView = ClubDynamicDetailommitView()
    private var commentModel = ClubGameDetailCommentListModel()
    private var replyCommentList:[ClubGameDetailCommentListModel] = []
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameDetailCommitTopCell.self,ClubGameDetailCommitSonCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 150.0.Scale
        return tableView
    }()
    
    var gameID = ""
    var gid: String = "" {
        didSet{
            loadData()
        }
    }
    private var gameModel: ClubNewHomeGameModel?
    private var pid = ""
    
    var updateDataBlock: (() -> Void)?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 禁用侧滑手势的代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 恢复默认代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            moreButton
            titleLabel
            tableView
            bottomView
            commitView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        moreButton.trailing(12.0.Scale).top(.statusHeight + 6.0.Scale).size(32.0.Scale)
        titleLabel.width(.screenWidth - 100.0).centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        tableView.leading(0).trailing(0).bottom(.tabBar_height).top(.navi_height)
        bottomView.leading(0).trailing(0).bottom(0).height(.tabBar_height)
        commitView.leading(0).width(.screenWidth).height(47.0.Scale).bottom(0)
        
        commitView.isHidden = true
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        bottomView.likeBlock = {
            self.likeCommit(commitID: self.commentModel.id)
        }
        bottomView.commitBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        commitView.sendTextBlock = { text in
            self.sendCommit(content: text)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    // 键盘消失时调用的方法
    @objc func keyboardWillHide(_ notification: Notification) {
        guard let userInfo = notification.userInfo else { return }

        self.commitView.isHidden = true
        self.bottomView.isHidden = false
    }
    
    @objc private func clickMoreButton(){
        let moreView = ClubGameMoreView()
        moreView.uid_des = commentModel.uid_des
        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = self.commentModel.id
                reportVC.type = "2"
                reportVC.updateDataBlock = {
                    self.navigationController?.popViewController(animated: true)
                }
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.delBlock = {
            Task{
                let res = await self.network.request(.delCommit(commitID: self.commentModel.id))
                if res.isSuccess {
                    "删除成功".toast_success
                    self.updateDataBlock?()
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }

        self.entryAnimate.animation(show: moreView)
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubGameDetailCommitDetailVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if replyCommentList.count == 0 {
            return 1
        }
        return replyCommentList.count + 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitTopCell", for: indexPath) as! ClubGameDetailCommitTopCell
            cell.model = commentModel
            cell.gameModel = gameModel
            cell.didSelectImage = { index,images in
                self.selectImage(index: index, images: images)
            }
            cell.popBlock = {
                let detailVC = ClubGameDetailViewController()
                detailVC.gameId = self.gameID
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameDetailCommitSonCell", for: indexPath) as! ClubGameDetailCommitSonCell
        cell.replyModel = self.replyCommentList[indexPath.row - 1]
//        cell.likeCommitBlock = {
//            self.updateDataBlock?()
//        }

        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row > 0 {
            
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let model = self.replyCommentList[indexPath.row - 1]
                self.commitView.commitView.placeHolder = "回复" + model.user_name
                self.pid = model.id
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
            
        }
    }

}

//MARK: action
extension ClubGameDetailCommitDetailVC {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}

extension ClubGameDetailCommitDetailVC {
        
    private func loadData(){
        ToastUtil.show()
        Task{
            let res = await self.network.requestMoreData(.getSonCommitList(pid: gid),type: ClubGameDetailCommentModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let data = res.model {
                guard let models = data.data, models.count > 0 else { return }
                let model = models[0]
                self.commentModel = model
                self.replyCommentList = model.son_list
                self.gameModel = data.game
                self.bottomView.commitModel = model
                self.pid = model.id
                self.tableView.reloadData()
            }
        }
    }
    
    private func likeCommit(commitID: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                let res = await self.network.request(.likeGameCommit(commitID: commitID))
                if res.isSuccess {
                    updateDataBlock?()
                    self.loadData()
                }
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
        
    }
    
    private func sendCommit(content: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                ToastUtil.show()
                
                let dict = ["content": content, "id": self.gameID, "pid": self.pid, "ppid": self.commentModel.id]
                let res = await self.network.requestSpecial(.commitGame(json: dict))
                self.pid = self.commentModel.id
                if res.isSuccess {
                    self.commitView.commitView.text = ""
                    self.commitView.commitView.placeHolder = "写点什么..."
                    loadData()
                }else{
                    res.errorMessage?.toast_error
                }
                ToastUtil.dismiss()
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }        
    }
}



class ClubGameDetailCommitSonCell: UITableViewCell, RaeNetworkProtocol {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let titleImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = ActiveLabel()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let contentLabel = ActiveLabel()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(10.font_medium).alignment(.right).end()
    private let likeButton = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    
    var likeCommitBlock: (() -> Void)?
    
    private var sonData: [ClubDynamicDetailCommentModel]?
    private var heightCache = [CGFloat]()
    
    
    var replyModel: ClubGameDetailCommentListModel? {
        didSet{
            guard let md = replyModel else { return }
            
            iconImageView.loadImage(url: md.touxiang)
            timeLabel.text = md.timetran
            var zan = md.zan
            if zan == "0"{
                zan = ""
            }
            subLabel.text = zan + "点赞"
            likeButton.isSelected = md.is_zan
            let name = "@" + md.beihuifu_user_name + ":"
            let content = "回复给@" + md.beihuifu_user_name + ":" + md.content
            configActiveStyle(name: name, content: content)
            var author = ""
            if  md.is_author {
                author = "作者 "
            }
            let user_Name = author + md.user_name
            configNameActiveStyle(name: author, content: user_Name)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = .white
        
        contentView.subviews{
            iconImageView
            nameLabel
            timeLabel
            contentLabel
            subLabel
            likeButton
        }
        
        iconImageView.leading(24.0.Scale).top(16.0.Scale).size(40.0.Scale)
        nameLabel.leading(76.0.Scale).top(22.0.Scale).trailing(15.0.Scale)
        timeLabel.leading(76.0.Scale).top(40.0.Scale).trailing(15.0.Scale)
        contentLabel.leading(76.0.Scale).top(56.0.Scale).trailing(16.0.Scale)
        likeButton.trailing(8.0.Scale).size(44.0.Scale).bottom(0)
        likeButton.Top == contentLabel.Bottom
        subLabel.trailing(56.0.Scale)
        subLabel.CenterY == likeButton.CenterY
        
        likeButton.addTarget(self, action: #selector(clickLikeButton), for: .touchUpInside)
    }
 
    @objc private func clickLikeButton(){
        
        if let ID = replyModel?.id {
            
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                Task{
                    let res = await self.network.request(.likeGameCommit(commitID: ID))
                    if res.isSuccess {
                        likeButton.isSelected = !likeButton.isSelected
                        if subLabel.text == "点赞" {
                            subLabel.text = "1点赞"
                        }else{
                            var zanString = subLabel.text ?? ""
                            if likeButton.isSelected {
                                zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                            }else{
                                zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                                if zanString == "0点赞"{
                                    zanString = "点赞"
                                }
                            }
                            subLabel.text = zanString
                        }
                    }
                }
            }else{
                UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        
        
    }
    
    private func configActiveStyle(name: String, content: String) {
        let customType = ActiveType.custom(pattern: "回复给")
        let customType1 = ActiveType.custom(pattern: name)
        contentLabel.isShowUnderLine = false
        contentLabel.font = 15.font_medium
        contentLabel.numberOfLines = 0
        contentLabel.textAlignment = .left
        contentLabel.enabledTypes = [customType, customType1]
        contentLabel.text = content
        contentLabel.textColor = "#4B4C4D".toColor
        contentLabel.customColor[customType] = "#7D7E80".toColor
        contentLabel.customColor[customType1] = "#3D9399".toColor
    }
    
    private func configNameActiveStyle(name: String, content: String) {
        let customType = ActiveType.custom(pattern: name)
        nameLabel.isShowUnderLine = false
        nameLabel.font = 12.font_semiBold
        nameLabel.numberOfLines = 0
        nameLabel.textAlignment = .left
        nameLabel.enabledTypes = [customType]
        nameLabel.text = content
        nameLabel.textColor = "#4B4C4D".toColor
        nameLabel.customColor[customType] = "#FF7500".toColor
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
